const { userModel, stuModel, orgInfoModel } = require('../../model');
const { getResultToObjectComplete } = require('../../services/utils');
const tokens = require('../../services/tokenService');
const number = require('../../services/learn_number');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

module.exports = {
  list: async (req, res) => {
    const attr = ['id','name','icon','logo','domain','expiration','createdAt'];
    // const org = await orgInfoModel.findAll(attr);

    const org = await orgInfoModel.findByRelation(attr, {},{
      model: userModel.getModel(),
      attributes: ['org', 'account'],
      where: { roles : { [Op.or]: ['org', 'school']}}
    });
    const list = getResultToObjectComplete(org, 'user', ['org', 'account']);
    // console.log(org)
    return res.send({
      code: 20000,
      data: {
        items: list
      }
    })
  },
  info: async (req, res) => {
    const { id } = req.params;
    const ORG = { org: id };
    const org = await orgInfoModel.findByRelation(['icon','name','domain','logo','expiration','createdAt'],{id: id}, {
      model: userModel.getModel(),
      attributes: ['id','account'],
      where: { roles : { [Op.or]: ['org', 'school']}}
    });
    const list = getResultToObjectComplete(org, 'user', ['id','account']);
    // const main = await userModel.findOne(['id', 'name', 'account', 'roles', 'createdAt'],ORG);
    // const student = await stuModel.findByFilter(['id', 'name', 'learn_number', 'grade', 'createdAt', 'updatedAt'],ORG);
    return res.send({
      code: 20000,
      data: list[0]
    })

  },
  create: async (req, res) => {
    const { name, icon, logo, domain, expiration, password } = req.body;
    try {
      const org = await orgInfoModel.create({
        name: name,
        icon: icon,
        logo: logo,
        domain: domain,
        expiration: expiration,
        createdAt: Date.now()
      });
      number.setCustomerType('org', async number => {
        const user = await userModel.create({
          name: name,
          account: number,
          password: password,
          avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
          roles: 'org',
          org: org.dataValues.id,
          updatedAt: Date.now(),
          createdAt: Date.now()
        });
        return res.send({
          code: 20000,
          data: {
            user: user,
            org: org
          }
        })
      });
    } catch (e) {
      console.error(e)
    }
  },
  delayExp: async (req, res) => {
    const id = req.params.id;
    let { model = 'add', delay = 'day' } = req.body;
    const timestamp = {
      day: 86400000,      // 增加一天
      week: 604800000,    // 增加一周
      month: 2592000000,  // 增加一个月
      half: 15552000000,  // 增加半年
      year: 31536000000   // 增加一年
    };
    if (!timestamp.hasOwnProperty(delay)) delay = 'day';
    try {
      const org = await orgInfoModel.findOne(['expiration'],{ id: id });
      let cur_timestamp = new Date(org.expiration).getTime();
      if (model === 'sub'){
        cur_timestamp -= timestamp[delay];
      } else{
        cur_timestamp += timestamp[delay];
      }
      const date = new Date(cur_timestamp);
      await orgInfoModel.update({expiration: date}, { id : id});
      return res.send({
        code: 20000,
        data: date
      })
    } catch (e) {
      console.error(e);
    }
  },
  resetPwd: async (req, res) => {
    const { id } = req.params;
    const { password } = req.body;

    try {
      await userModel.update({ password: password }, { id: id});
      return  res.send({
        code: 20000
      })
    } catch (e) {
      console.error(e)
    }
  },
  update: async (req, res) => {
    const { id } = req.params;
    const { name, icon, logo, domain, expiration } = req.body;
    // TODO 日期格式校验
    try {
      await orgInfoModel.update({
        name: name,
        icon: icon,
        logo: logo,
        domain: domain,
        expiration: expiration
      },{
        id: id
      });
      return res.send({
        code: 20000
      })
    } catch (e) {
      console.error(e);
    }
  }
  // delete: async (req, res) => {
  //   const { id } = req.params;
  //   const { password } = req.body;
  //
  //   try {
  //     const admin = await userModel.findOne(['id'], { account: 'admin', password: password});
  //     if (!admin) return res.send({
  //       code: 10000,
  //       msg: '管理密码错误'
  //     })
  //
  //   } catch (e) {
  //     console.error(e);
  //   }
  // }
};
